package com.heatup.apt.api.controller;

import com.heatup.apt.api.service.CompanyInfoService;
import com.heatup.apt.api.service.CompanyStaffService;
import com.heatup.apt.common.constants.ErrorCodeConstants;
import com.heatup.apt.common.constants.UserConstants;
import com.heatup.apt.common.dao.SmsLogMapper;
import com.heatup.apt.common.util.*;
import com.heatup.apt.model.SmsLog;
import com.heatup.apt.model.api.ApiResultModel;
import com.heatup.apt.model.company.CompanyInfo;
import com.heatup.apt.model.company.CompanyStaff;
import com.heatup.apt.model.user.UserInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by blank on 2017/1/16.
 */
@RequestMapping(value = "/company")
@Controller
public class CompanyController extends BaseController {

    protected static final Logger log = LoggerFactory.getLogger(CompanyController.class);
    
    @Autowired
    private CompanyInfoService companyInfoService;

    @Autowired
    private CompanyStaffService companyStaffService;

    @Autowired
    private SmsLogMapper smsLogMapper;


    /**
     * 发送验证码
     *
     * @param mobile 手机号
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/send", method = {RequestMethod.POST, RequestMethod.GET})
    private String send(
            @RequestParam() String mobile,
            @RequestParam(defaultValue = "") String callback) {
        Integer userId = this.getUserId();

        ApiResultModel<Map<String, Object>> apiResultModel = new ApiResultModel<>(this.isLogined());

        //未登陆
        if (userId == null) {
            apiResultModel.setRet(ApiResultModel.RET_ERROR);
            apiResultModel.setMsg(ErrorCodeConstants.Code.USER_NOT_LOGIN.getMessage());
            apiResultModel.setErrorCode(ErrorCodeConstants.Code.USER_NOT_LOGIN.getCode());
            return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);
        }


        try {
            //检查发送间隔
            Object lastSend = this.getSession(SESSION_KEY_CHECK_CODE_LAST_SEND);
            if (lastSend != null) {
                long lastSendTime = (long) lastSend;
                long currentTime = System.currentTimeMillis();
                long seconds = (currentTime - lastSendTime) / 1000;
                if (seconds < UserConstants.SEND_CHECK_CODE_INTERVAL) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("nextSendSecond", seconds);
                    apiResultModel.setData(map);
                    apiResultModel.setRet(ApiResultModel.RET_ERROR);
                    apiResultModel.setMsg(ErrorCodeConstants.Code.SMS_SEND_TOO_MUCH.getMessage());
                    apiResultModel.setErrorCode(ErrorCodeConstants.Code.SMS_SEND_TOO_MUCH.getCode());

                    return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);
                }
            }

            //检查发送限额
            int todayMyCount = smsLogMapper.querySmsCountByUserMobile(mobile);
            if (todayMyCount > UserConstants.CHECK_CODE_MAX_SEND_COUNT) {

                Map<String, Object> map = new HashMap<>();
                apiResultModel.setData(map);
                apiResultModel.setRet(ApiResultModel.RET_ERROR);
                apiResultModel.setMsg(ErrorCodeConstants.Code.SMS_SEND_OVER_LIMIT.getMessage());
                apiResultModel.setErrorCode(ErrorCodeConstants.Code.SMS_SEND_OVER_LIMIT.getCode());
                return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);
            }

            Map<String, Object> map = new HashMap<>();

            int checkCode = CheckCodeUtil.getCheckCode();
            boolean sendResult = SmsUtil.sendCheckCode(mobile, checkCode + "");

            //发送记录
            SmsLog smsLog = new SmsLog();
            smsLog.setMobile(mobile);
            smsLog.setCheckCode(checkCode + "");
            smsLog.setUserId(userId);
            smsLog.setSendTime(new Date());
            smsLog.setSendResult(sendResult ? 1 : 2);
            smsLogMapper.insertSelective(smsLog);

            this.setSession(SESSION_KEY_MOBILE, mobile);
            this.setSession(SESSION_KEY_CHECK_CODE, checkCode);
            this.setSession(SESSION_KEY_CHECK_CODE_LAST_SEND, System.currentTimeMillis());
            map.put("nextSendSecond", UserConstants.SEND_CHECK_CODE_INTERVAL);

            apiResultModel.setData(map);
            apiResultModel.setRet(ApiResultModel.RET_SUCCESS);
            apiResultModel.setMsg("");
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.toString() + e.getCause(),e);
            apiResultModel.setRet(ApiResultModel.RET_ERROR);
            apiResultModel.setMsg(ErrorCodeConstants.Code.SYSTEM_ERROR_EXCEPTION.getMessage() + e.toString() + e.getCause());
        }

        return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);
    }

    /**
     * 校验验证码
     *
     * @param checkCode 验证码
     * @param callback  回调
     * @return success --> true 校验成功/ false 校验失败
     */
    @ResponseBody
    @RequestMapping(value = "/check", method = {RequestMethod.POST, RequestMethod.GET})
    private String checkCheckCode(String checkCode, String callback) {

        Integer userId = this.getUserId();

        ApiResultModel<Map<String, Object>> apiResultModel = new ApiResultModel<>(this.isLogined());

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("success", false);

        //未登陆
        if (userId == null) {
            apiResultModel.setRet(ApiResultModel.RET_ERROR);
            apiResultModel.setMsg(ErrorCodeConstants.Code.USER_NOT_LOGIN.getMessage());
            apiResultModel.setErrorCode(ErrorCodeConstants.Code.USER_NOT_LOGIN.getCode());
            return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);
        }

        try {
            //有效期验证
            Object syscode = this.getSession(SESSION_KEY_CHECK_CODE);
            Object lastSend = this.getSession(SESSION_KEY_CHECK_CODE_LAST_SEND);
            if (syscode == null || lastSend == null) {
                apiResultModel.setRet(ApiResultModel.RET_ERROR);
                apiResultModel.setMsg(ErrorCodeConstants.Code.SMS_CHECK_CODE_NULL.getMessage());
                apiResultModel.setErrorCode(ErrorCodeConstants.Code.SMS_CHECK_CODE_NULL.getCode());
                return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);
            }

            long lastSendTime = (long) lastSend;
            long currentTime = System.currentTimeMillis();
            long seconds = (currentTime - lastSendTime) / 1000;
            if (seconds > UserConstants.CHECK_CODE_TIMEOUT) {
                apiResultModel.setRet(ApiResultModel.RET_ERROR);
                apiResultModel.setMsg(ErrorCodeConstants.Code.SMS_CHECK_CODE_INVALID.getMessage());
                apiResultModel.setErrorCode(ErrorCodeConstants.Code.SMS_CHECK_CODE_INVALID.getCode());
                return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);
            }

            //验证码验证
            if (syscode.toString().length() > 0 && syscode.toString().equals(checkCode)) {
                apiResultModel.setRet(ApiResultModel.RET_SUCCESS);
                apiResultModel.setMsg("验证成功");
                resultMap.put("success", true);
                apiResultModel.setData(resultMap);

            } else {
                apiResultModel.setRet(ApiResultModel.RET_ERROR);
                apiResultModel.setMsg(ErrorCodeConstants.Code.SMS_CHECK_CODE_ERROR.getMessage());
                apiResultModel.setErrorCode(ErrorCodeConstants.Code.SMS_CHECK_CODE_ERROR.getCode());
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.toString() + e.getCause(),e);
            apiResultModel.setRet(ApiResultModel.RET_ERROR);
            apiResultModel.setMsg(ErrorCodeConstants.Code.SYSTEM_ERROR_EXCEPTION.getMessage() + e.toString() + e.getCause());
        }

        return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);
    }

    /**
     * 绑定企业
     *
     * @param companyStaff 企业员工 --> 企业ID 企业员工手机号
     * @return success -->true成功/false失败
     */
    @RequestMapping(value = "/bindingCompany")
    @ResponseBody
    public String bandingCompany(CompanyStaff companyStaff, String callback) {

        ApiResultModel<Map<String, Object>> apiResultModel = new ApiResultModel<>(this.isLogined());
        try {
            apiResultModel.setData(companyStaffService.bandingCompany(companyStaff, getUserInfo()));
            apiResultModel.setRet(ApiResultModel.RET_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.toString() + e.getCause(),e);
            apiResultModel.setRet(ApiResultModel.RET_ERROR);
            apiResultModel.setMsg(ErrorCodeConstants.Code.SYSTEM_ERROR_EXCEPTION.getMessage() + e.toString() + e.getCause());
        }
        return ResponseTools.CallBackResultJsonP(JsonUtils.toJsonStrWithDateFormat(apiResultModel), callback);
    }


    /**
     * 企业支付详情
     *
     * @param callback 回调
     * @return
     */
    @RequestMapping(value = "/companyPaymentDetail")
    @ResponseBody
    public String companyPaymentDetail(String callback) {

        ApiResultModel<Map<String, Object>> apiResultModel = new ApiResultModel<>(this.isLogined());

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("success", false);
        UserInfo companyStaffUser = getUserInfo();
        if (companyStaffUser == null) {
            resultMap.put("msg", "用户未登陆!");
        } else if (companyStaffUser.getId() != null) {
            CompanyStaff companyStaff = companyStaffService.selectCompanyPaymentDetailByUserId(getUserId());
            if (companyStaff != null) {
                resultMap.put("success", true);
                resultMap.put("companyStaff", companyStaff);
            }
        }
        apiResultModel.setData(resultMap);
        return ResponseTools.CallBackResultJsonP(JsonUtils.toJsonStrWithDateFormat(apiResultModel), callback);
    }


    /**
     * 企业详情接口
     *
     * @param companyId 企业ID
     * @return 企业详情
     */
    @RequestMapping(value = "/companyInfo")
    @ResponseBody
    public String companyInfo(@RequestParam Long companyId, String callback) {

        ApiResultModel<CompanyInfo> apiResultModel = new ApiResultModel<>(this.isLogined());

        CompanyInfo companyInfo = null;
        try {
            companyInfo = new CompanyInfo();
            companyInfo.setId(companyId);
            companyInfo.setStatus(1);
            companyInfo = companyInfoService.selectOne(companyInfo);
            apiResultModel.setData(companyInfo);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.toString() + e.getCause(),e);
            apiResultModel.setRet(ApiResultModel.RET_ERROR);
            apiResultModel.setMsg(ErrorCodeConstants.Code.SYSTEM_ERROR_EXCEPTION.getMessage() + e.toString() + e.getCause());

        }
        return ResponseTools.CallBackResultJsonP(JsonUtils.toJsonStrWithDateFormat(companyInfo), callback);
    }


    /**
     * 个人---> 企业储值卡消费记录
     *
     * @param callback 回调
     * @return 个人企业储值卡消费记录
     */
    @RequestMapping(value = "/personOrderList")
    @ResponseBody
    public String companyValuedOrderList(@RequestParam Integer pageIndex, @RequestParam Integer pageSize, String callback) {
        ApiResultModel<Object> apiResultModel = new ApiResultModel<>(this.isLogined());
        try {
            apiResultModel.setData(companyStaffService.companyValuedOrderList(pageIndex, pageSize, getUserId()));
            apiResultModel.setMsg("success");
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.toString() + e.getCause(),e);
            apiResultModel.setMsg(ErrorCodeConstants.Code.SYSTEM_ERROR_EXCEPTION.getMessage() + e.toString() + e.getCause());
            apiResultModel.setErrorCode(ErrorCodeConstants.Code.SYSTEM_ERROR_EXCEPTION.getCode());
        }
        return ResponseTools.CallBackResultJsonP(JsonUtils.toJsonStrWithDateFormat(apiResultModel), callback);

    }
}

